package cn.jn.lhm.part02;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.StandardProtocolFamily;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

import static cn.jn.lhm.part01.ByteBufferUtil.debugRead;

/**
 * @author lhm 2753914576@qq.com
 * @time 2023/4/5 - 20:38
 **/
@Slf4j
public class Server {
    public static void main(String[] args) throws IOException {
        ByteBuffer buffer = ByteBuffer.allocate(1024);

        // 创建Server端
        ServerSocketChannel ssc = ServerSocketChannel.open();

        // 绑定本地端口并设置非阻塞模式
        ssc.bind(new InetSocketAddress(8080));
        ssc.configureBlocking(false);

        // 创建集合处理所有的客户端
        List<SocketChannel> channelClients = new ArrayList<>();

        while (true) {
            // 接收客户端设置非阻塞读取
            SocketChannel client = ssc.accept();
            if (client != null) {
                log.info("客户端:{}连接成功", client);
                client.configureBlocking(false);
                channelClients.add(client);
            }

            for (SocketChannel channelClient : channelClients) {
                if (channelClient.read(buffer) != 0) {
                    buffer.flip();
                    debugRead(buffer);
                    log.info("收到客户端:{}的消息:{}", channelClient, StandardCharsets.UTF_8.decode(buffer));
                    buffer.clear();
                }
            }
        }
    }

}
